package org.scboy.dbms.valid.common;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import org.scboy.dbms.annotation.ValidType;
import org.scboy.dbms.entity.ParamConfig;
import org.scboy.dbms.valid.Valid;
import org.scboy.utils.entitys.coobi.Model;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;

@ValidType("数组长度校验")
public class ArrayLengValid implements Valid {

	@Override
	public List<ParamConfig> config() {
		List<ParamConfig> ParamConfigs=new ArrayList<ParamConfig>();
		ParamConfigs.add(new ParamConfig("expression", "表达式","长度表达式，格式min:固定长度,min-max:范围长度"));
		return ParamConfigs;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public boolean valid(Object data,Model model,Model config) {
		String expression=config.getString("expression");
		//为null或者表达式为空，跳过
		if(data!=null&&StrUtil.isNotEmpty(expression)){
			
			if(data instanceof List || data instanceof Array) {
				//String value=Convert.toStr(data);
				int length=0;
				if(data instanceof List) {
					length=((List)data).size();
				}else if( data instanceof Array) {
					length=((Object [])data).length;
				}
				if(expression.indexOf("-")>-1){
					//验证范围
					String [] arrays=expression.split("-");
					Integer min=Convert.toInt(arrays[0]);
					Integer max=Convert.toInt(arrays[1]);
					if(length<min || length > max){
						return false;
					}
				}else{
					//验证长度
					Integer maxLeng=Convert.toInt(expression);
					//值的字符串长度不等于配置长度
					if(length!=maxLeng){
						return false;
					}
				}
			}else {
				return false;
			}
		}
		return true;
	}
	
	@Override
	public String toString(Model config) {
		String expression=config.getString("expression");
		//验证范围
		if(expression.indexOf("-")>-1){
			String [] arrays=expression.split("-");
			Integer min=Convert.toInt(arrays[0]);
			Integer max=Convert.toInt(arrays[1]);
			return StrUtil.format("长度必须在{}-{}范围内", min,max);
		}else{
			return StrUtil.format("长度必须等于{}", expression);
		}
	}
}
